﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;

namespace PRE.Catalog
{
    /// <summary>
    /// Author:		Nguyen Van Toan
    /// Email:		nvt87x@gmail.com
    /// Phone:		01645 515 010
    /// Create:		19/02/2012 08:00 AM
    /// Update:		?
    /// User form: catalog of users
    /// </summary>
    public partial class FrmUser : PRE.Catalog.FrmBase
    {
        private const string STR_ADD = "Thêm người dùng";
        private const string STR_EDIT = "Sửa người dùng";
        private const string STR_DELETE = "Xoá người dùng";

        private const string STR_SELECT = "Chọn dữ liệu!";
        private const string STR_CONFIRM = "Có xoá tài khoản '{0}' không?";
        private const string STR_UNDELETE = "Không xoá được!\nDữ liệu đang được sử dụng.";
        private const string STR_DUPLICATE = "Tài khoản này có rồi";
        private const string STR_EMPTY = "Chưa nhập [{0}]";

        private const string STR_PASS = "Mật khẩu 6 kí tự trở lên!";

        public FrmUser()
        {
            InitializeComponent();

            grvMain.OptionsBehavior.Editable = false;
            _bll = new BLL.UserBLL();
        }

        private void FrmUser_Load(object sender, EventArgs e)
        {
            lokRole.Properties.DataSource = new BLL.RoleBLL().Select();
            if (lokRole.Properties.DropDownRows > 2) lokRole.ItemIndex = 3; // none
        }

        #region Override
        /// <summary>
        /// Perform when click add button
        /// </summary>
        protected override void PerformAdd()
        {
            base.PerformAdd();
        }

        /// <summary>
        /// Perform when click cancel button
        /// </summary>
        protected override void PerformCancel()
        {
            base.PerformCancel();
        }

        /// <summary>
        /// Perform when click delete button
        /// </summary>
        /// <returns></returns>
        protected override void PerformDelete()
        {
            var tmp = grvMain.GetFocusedRowCellValue("Id") + "";
            long id = UTL.Number.ToInt64(tmp);

            if (id == 0) UTL.Message.Show(STR_SELECT, STR_DELETE);
            else
            {
                var cfm = String.Format(STR_CONFIRM, txtName.Text);
                var oki = UTL.Message.Show(cfm, STR_DELETE, MessageBoxButtons.OKCancel);

                if (oki == DialogResult.OK)
                    if (_bll.Delete(id) == UTL.Session.PerState.Success) PerformRefresh();
                    else UTL.Message.Show(STR_UNDELETE, STR_DELETE);
            }

            base.PerformDelete();
        }

        /// <summary>
        /// Perform when click edit button
        /// </summary>
        protected override void PerformEdit()
        {
            base.PerformEdit();
        }

        protected override void PerformFind()
        {
            base.PerformFind();
        }

        /// <summary>
        /// Perform when click print button
        /// </summary>
        protected override void PerformPrint()
        {
            base.PerformPrint();
        }

        /// <summary>
        /// Load data or perform when click refresh button
        /// </summary>
        protected override void PerformRefresh()
        {
            LoadData();

            if (_dtb != null)
            {
                // Binding data
                ClearDataBindings();
                if (_dtb.Rows.Count > 0) DataBindingControl();
            }
            base.PerformRefresh();
        }

        /// <summary>
        /// Perform when click save button
        /// </summary>
        protected override void PerformSave()
        {
            switch (_frmState)
            {
                case UTL.Session.FormState.Add:
                    if (InsertObject())
                    {
                        ResetText(); LoadData();
                    }
                    break;

                case UTL.Session.FormState.Edit:
                    if (UpdateObject())
                    {
                        ChangeStatus(); ReadOnlyControl();
                        PerformRefresh();
                    }
                    break;
            }

            base.PerformSave();
        }

        /// <summary>
        /// Reset all input control
        /// </summary>
        protected override void ResetText()
        {
            txtName.Text = null;
            txtAcc.Text = null;
            txtPass.Text = null;
            if (lokRole.Properties.DropDownRows > 2) lokRole.ItemIndex = 3; // none

            base.ResetText();
        }

        /// <summary>
        /// Clear data binding
        /// </summary>
        protected override void ClearDataBindings()
        {
            txtName.DataBindings.Clear();
            txtAcc.DataBindings.Clear();
            txtPass.DataBindings.Clear();
            lokRole.DataBindings.Clear();

            base.ClearDataBindings();
        }

        /// <summary>
        /// Add data binding
        /// </summary>
        protected override void DataBindingControl()
        {
            txtName.DataBindings.Add("EditValue", _dtb, ".Name");
            txtAcc.DataBindings.Add("EditValue", _dtb, ".Acc");
            txtPass.DataBindings.Add("EditValue", _dtb, ".Pass");
            lokRole.DataBindings.Add("EditValue", _dtb, ".Role");

            base.DataBindingControl();
        }

        /// <summary>
        /// Set read only control on form
        /// </summary>
        /// <param name="isReadOnly">Read only is trule else normal</param>
        protected override void ReadOnlyControl(bool isReadOnly = true)
        {
            txtName.Properties.ReadOnly = isReadOnly;
            txtPass.Properties.ReadOnly = isReadOnly;
            lokRole.Properties.ReadOnly = isReadOnly;

            // Not allow to edit Acc
            if (_frmState == UTL.Session.FormState.Edit) txtAcc.Properties.ReadOnly = true;
            else txtAcc.Properties.ReadOnly = isReadOnly;

            grcMain.Enabled = isReadOnly;

            base.ReadOnlyControl(isReadOnly);
        }

        /// <summary>
        /// Update object
        /// </summary>
        /// <returns>True if successful else false</returns>
        protected override bool UpdateObject()
        {
            try
            {
                if (!ValidInput()) return false;

                var tmp = grvMain.GetFocusedRowCellValue("Id") + "";
                long id = UTL.Number.ToInt64(tmp);

                var o = new DAL.tb_User()
                {
                    Id = id,
                    Name = txtName.Text,
                    Acc = txtAcc.Text,
                    Pass = txtPass.Text,
                    Role = UTL.Number.ToInt64(lokRole.EditValue + "")
                };

                var oki = _bll.Update(o);
                if (oki == UTL.Session.PerState.Duplicate)
                    UTL.Message.Show(STR_DUPLICATE, STR_EDIT);
                return oki == UTL.Session.PerState.Success ? true : false;
            }
            catch { return false; }
        }

        /// <summary>
        /// Delete object
        /// </summary>
        /// <returns>True if successful else false</returns>
        protected override bool InsertObject()
        {
            try
            {
                if (!ValidInput()) return false;

                var o = new DAL.tb_User()
                {
                    Name = txtName.Text,
                    Acc = txtAcc.Text,
                    Pass = txtPass.Text,
                    Role = UTL.Number.ToInt64(lokRole.EditValue + "")
                };

                var oki = _bll.Insert(o);
                if (oki == UTL.Session.PerState.Duplicate)
                    UTL.Message.Show(STR_DUPLICATE, STR_ADD);
                return oki == UTL.Session.PerState.Success ? true : false;
            }
            catch { return false; }
        }

        /// <summary>
        /// Load data
        /// </summary>
        protected override void LoadData()
        {
            _dtb = _bll.Select();

            if (_dtb != null)
            {
                grcMain.DataSource = _dtb;
                gridColumn2.BestFit(); // fit column
            }

            base.LoadData();
        }

        /// <summary>
        /// Valid data before insert or update to database
        /// </summary>
        /// <returns>True if valid else false</returns>
        protected override bool ValidInput()
        {
            if (txtName.Text + "" == "")
            {
                UTL.Message.Show(String.Format(STR_EMPTY, lblName.Text), STR_ADD);
                txtName.Focus();
                return false;
            }

            if (txtAcc.Text + "" == "")
            {
                UTL.Message.Show(String.Format(STR_EMPTY, lblAcc.Text), STR_ADD);
                txtAcc.Focus();
                return false;
            }

            // Password length minimum 6
            if ((txtPass.Text + "").Length < 6)
            {
                UTL.Message.Show(STR_PASS, STR_ADD);
                txtPass.Focus();
                return false;
            }

            return base.ValidInput();
        }
        #endregion
    }
}